<template>
  <div>
    <Card class="warp-card" dis-hover>
      <Form class="tools" inline>
        <FormItem v-privilege="'people-query'">
          <Input placeholder="请输入用户信息" v-model="searchData.keyWord" clearable></Input>
        </FormItem>
        <FormItem prop="sendStatus">
          <!--<Select placeholder="请选择所属部门" style="width:200px" v-model="searchData.department" clearable>
            <Option :value="1">已发送</Option>
            <Option :value="0">未发送</Option>
          </Select>-->
          <Cascader placeholder="请选择所属部门" :data="deptData" v-model="searchData.departmentNames"
                    trigger="hover" change-on-select
                    @on-change="handleChange"></Cascader>
        </FormItem>
        <FormItem prop="sendStatus">
          <Select placeholder="请选择用户状态" style="width:200px" v-model="searchData.isDisabled"
                  @on-change="getStatus($event)" clearable>
            <Option :value="1">启用</Option>
            <Option :value="2">失效</Option>
          </Select>
        </FormItem>
        <FormItem prop="startDate">
          <DatePicker placeholder="请选择注册时间" type="datetime" v-model="searchData.startDate"></DatePicker>
        </FormItem>
        <FormItem>
          <ButtonGroup>
            <Button
              @click="getPeopleList"
              icon="ios-search"
              type="primary"
              v-privilege="'people-query'"            >查询</Button>
            <Button
              @click="refresh"
              icon="md-refresh"
              type="default"
              v-privilege="'people-query'"            >重置</Button>
          </ButtonGroup>
        </FormItem>
        <FormItem>
          <Button
            @click="openModal('add')"
            icon="md-add"
            type="primary"
            v-privilege="'people-add'"          >添加用户</Button>
        </FormItem>
      </Form>
      <Table :columns="columns" :data="data" :loading="loading"
             @on-sort-change="handleSortChange"
             @on-selection-change="selectChange"
             border stripe highlight-row
             no-data-text="暂无数据"></Table>
      <Page
        :current="pageNum"
        :page-size="pageSize"
        :page-size-opts="[10, 20, 30, 50, 100]"
        :total="pageTotal"
        @on-change="changePage"
        @on-page-size-change="changePageSize"
        show-elevator
        show-sizer
        show-total
        style="margin:24px 0;text-align:right;"
      ></Page>
    </Card>
    <!-- 添加/修改用户 -->
    <Modal
      :loading="saveLoading"
      :title="modalType=='add'?'添加用户':'修改用户'"
      @on-cancel="cancelSave"
      @on-ok="addOrUpdatePeople"
      v-model="editModal"
    >
      <Form :label-width="80" :model="formData" :rules="formValidate" ref="formRef">
        <FormItem label="用户名" prop="title">
          <Input placeholder="请输入用户名" v-model="formData.title"></Input>
        </FormItem>
        <FormItem label="姓名" prop="title">
          <Input placeholder="请输入姓名" v-model="formData.title"></Input>
        </FormItem>
        <FormItem label="手机号" prop="title">
          <Input placeholder="请输入手机号" v-model="formData.title"></Input>
        </FormItem>
        <FormItem label="邮箱" prop="">
          <Input placeholder="请输入邮箱" v-model="formData.title"></Input>
        </FormItem>
        <FormItem label="部门" prop="sendStatus">
          <Cascader placeholder="请选择所属部门" :data="deptData" v-model="searchData.departmentNames"
                    trigger="hover" change-on-select
                    @on-change="handleChange">
          </Cascader>
        </FormItem>
        <FormItem label="备注" prop="content">
          <Input  :autosize="{minRows: 2,maxRows: 5}"
            placeholder="请输入备注"
            type="textarea"
            v-model="formData.content"          ></Input>
        </FormItem>
      </Form>
    </Modal>
    <!-- 添加修改消息 -->
  </div>
</template>

<script>
  import { peopleApi } from '@/api/people';
  // import { NOTICE_STATUS } from '@/constants/people';
  export default {
    name: 'PeopleList',
    components: {},
    props: {},
    data() {
      return {
        // 查询参数
        searchData: {
          pageNum: 1,
          pageSize: 10,
          departmentNames: null, // 部门名称
          isDisabled: null, // 用户状态：0：新建，1：启用，2：失效；    发送状态 0未发送 1已发送
          keyWord: null
          // searchCount: true, // 是否查询总条数
          // startDate: null,
          // endDate: null,
          // orders: [],
          // title: '',
        },
        modalType: 'add',
        editModal: false,
        addModal: false,
        loading: true,
        saveLoading: true,
        updateLoading: true,
        pageNum: 1,
        pageSize: 10,
        pageTotal: 0,
        updateItem: {},
        saveItem: {},
        formData: {
          title: '',
          content: ''
        },
        sortType: 'normal', // normal || asc || desc
        // table表头
        columns: [
          {
            type: 'selection',
            width: 30,
            align: 'center'
          },   {
            title: 'ID',
            width: 60,
            key: 'userId',
            // tableColumn: 't_peony.id',
            // tableColumn: 'userId',
            render: (h, params) => {
              return h("span", params.index + (this.pageNum - 1) * this.pageSize + 1);
            }
          },   {
            title: '用户名',
            tableColumn: 'userName',
            key: 'userName',
            sortable: 'custom'
          },   {
            title: '姓名',
            tableColumn: 'actualName',
            key: 'actualName'
          },   {
            title: '手机号',
            tableColumn: 'phone',
            key: 'phone'
          },  {
            title: '邮箱',
            tableColumn: 'email',
            key: 'email'
          },  {
            title: '所属部门',
            tableColumn: 'departmentName',
            key: 'departmentName'
          },   {
            title: '注册时间',
            tableColumn: 'createTime',
            key: 'createTime',
            sortable: 'custom'
          },   {
            title: '用户状态',
            tableColumn: 'isDisabled',
            key: 'isDisabled',
            width: 77,
            render(h, params) {
              let str = params.row.isDisabledShow;
              return h('span', {}, str);
            }
          },
          /*{
            title: '是否发送',
            key: 'sendStatus',
            render: (h, params) => {
              return h(     'span',    this.$enum.getDescByValue('NOTICE_STATUS', params.row.sendStatus)    );
            }
          },*/
          {
            title: '操作',
            key: 'action',
            align: 'center',
            width: 77,
            className: 'action-hide',
            render: (h, params) => {
              let btns = [
                {
                  title: '详情',
                  directives: [
                    {
                      name: 'privilege',
                      value: 'people-detail'
                    }
                  ],
                  action: () => {
                    this.$router.push({
                      name:'PeopleDetail',
                      params:{people:params.row}
                    })
                  }
                },
                {
                  title: '删除',
                  directives: [
                    {
                      name: 'privilege',
                      value: 'people-delete'
                    }
                  ],
                  action: () => {
                    this.$Modal.confirm({
                      title: '删除',
                      content: '确认删除该条消息么？',
                      onOk: () => {
                        this.deletePeople(params.row.id);
                      }
                    });
                  }
                }
              ];
              let editBtn = {
                title: '编辑',
                directives: [
                  {
                    name: 'privilege',
                    value: 'people-edit'
                  }
                ],
                action: () => {
                  this.openModal('edit', params.row);
                }
              };
              // let sendBtn = {
              //   title: '发送',
              //   directives: [   {    name: 'privilege',   value: 'people-send'   }    ],
              //   action: () => {
              //     this.$Modal.confirm({
              //       title: '确认',    content: '确认发送条消息么？',
              //       onOk: () => {    this.sendPeople(params.row.id);     }
              //     });
              //   }
              // };
              // if (params.row.sendStatus != NOTICE_STATUS['YES'].value) {   btns.push(editBtn); }
              // if (params.row.sendStatus != NOTICE_STATUS['YES'].value) {   btns.push(sendBtn); }
              return this.$tableAction(h, btns);
            }
          }
        ],
        // table数据
        data: [],
        // 部门选择框参数
        departmentNames: [],
        deptData: [],
        formValidate: {
          title: [{ required: true, message: '请输入消息标题', trigger: 'blur' }],
          content: [
            { required: true, message: '请输入消息内容', trigger: 'blur' }
          ]
        }
      };
    },
    computed: {
      limitData() {
        let data = [...this.data];
        if (this.sortType === 'asc') {
          data = data.sort((a, b) => {
            return a.number > b.number ? 1 : -1;
          })
        }
        if (this.sortType === 'desc') {
          data = data.sort((a, b) => {
            return a.number < b.number ? 1 : -1;
          })
        }
// if (this.filterType === 1) {  data = data.filter(item => {  return item.status === 1;   })
// } else if (this.filterType === 2) {  data = data.filter(item => {  return item.status === 2;  })
// } else if (this.filterType === 3) {  data = data.filter(item => {  return item.status === 3;  })     }
        return data;
      }
    },
    watch: {},
    filters: {},
    created() {},
    mounted() {
      this.getPeopleList();
      this.queryDepartmentById();
      this.getStatus();
    },
    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    methods: {
      // 查询用户列表
      async getPeopleList() {
        try {
          this.loading = true;
          let result = await peopleApi.getPeopleList({
            ...this.searchData,
            pageNum: this.pageNum,
            pageSize: this.pageSize
          });
          // console.log("---------------------------", departmentName[departmentName.length-1])
          this.loading = false;
          this.data = result.result.list;
          this.pageTotal = result.result.total;
          this.pageNum = result.result.pageNum;
          this.pageSize = result.result.pageSize;
        } catch (e) {
          //TODO zhuoda sentry
          console.error(e);
        }
      },
      // 获取部门名称
      async queryDepartmentById() {
        let result = await peopleApi.queryDepartmentById();

        result = JSON.parse(JSON.stringify(result).replace(/parentId/g,"value").
                                                   replace(/name/g,"label"));
        // result = JSON.parse(JSON.stringify(value).replace(/name/g,"label"));
        this.deptData  = result;
      },
      handleChange (value, selectedData) {
        this.text = selectedData.map(o => o.label).join(', ');
        console.log("------value------", value);
        console.log("------this.text------", this.text);
      },

      getStatus(event) {
        console.log("------event------", event);
        console.log("-----searchData.isDisabledShow-------", this.searchData.isDisabledShow);
      },

      //处理排序
      handleSortChange(column) {
        debugger
        if (column.order === 'normal') {
          this.searchData.orders = [];
        } else {
          this.searchData.orders = [
            {
              column: column.column.tableColumn,
              asc: 'asc' === column.order
            }
          ];
        }
        this.getPeopleList();
      },
      //  这个函数就放在你点击翻页的函数里就行了（需要注意要在table将数据渲染完毕后执行，否则报错），
      //  达到每次翻页加载时将以前选中的row勾选上的效果
      // 给跨页丢失的选中行重新添加选中状态
      setChecked () {
        // 找到绑定的table的ref对应的dom，找到table的objData对象，objData保存的是当前页的数据
        //objData是vue自带的对象，直接.出来就可以了
        let objData = this.$refs.optTableList.objData;
        for (let index in objData) {
          if (this.selectedIds.has(objData[index].id)) {
            objData[index]._isChecked = true;//_isChecked是vue自带属性
            // this.$refs.optTableList.toggleSelect(index)
          }
        }
      },
      selectChange(selection){
        //保存勾选过的数据，防止翻页后勾选过的数据消失
        const that = this;
        const tempList = that.$refs.optTableList.getSelection();

        //去重
        var flag;
        for(let i = 0 ; i < tempList.length;i++ ){
          flag = true;
          for (var j in that.temporaryList){
            if (tempList[i].id === that.temporaryList[j].expertId){
              flag = false;
              break;
            }
          }
          if (flag){
            tempList[i].type = 0;//默认为组员
            tempList[i].expertId = tempList[i].id;
            tempList[i].projectId = that.expertRequest.projectId;
            tempList[i].id = "";
            that.temporaryList.push(tempList[i]);
            that.optExpertRequest.ids.push(tempList[i].id);
          }
        };

        //把勾选过然后再取消勾选的数据删除
        var index = [];//下标
        for (var i in that.temporaryList){
          var count = 0;//记数器
          for(var j of that.selectedIds){//当temporaryList中的某一元素不等于selectedIds中所有元素时，记下下标
            if(that.temporaryList[i].expertId !== j){//temporaryList的第i位不等于selectedIds的第j位时count+1
              count = count+1;
            }
            if(count === that.selectedIds.size){//当temporaryList的第i位不等于selectedIds中所有的元素时,说明temporaryList的第i位不存在selectedIds中，故删去
              index.push(parseInt(i));
            }
          }
        };
        if (index !== null && index.length > 0){
          for(i in index){
            that.optExpertRequest.ids.splice(index[i], 1);//删去多余的元素
            that.temporaryList.splice(index[i], 1);//删去多余的元素
          }
        }
      },

      // 获取通知详情
      async getPeopleDetail(id) {
        try {
          this.loading = true;
          let result = await peopleApi.getPeopleDetail(id);
          this.loading = false;
          this.formData = result.data;
        } catch (e) {
          this.loading = true;
          //TODO zhuoda sentry
          console.error(e);
        }
      },
      // 添加消息
      openModal(type, data) {
        this.modalType = type;
        switch (type) {
          case 'add':
            this.formData = {};
            this.editModal = true;
            break;
          case 'edit':
            this.getPeopleDetail(data.id);
            this.editModal = true;
            break;
        }
      },
      // 分页
      changePage(pageNum) {
        this.pageNum = pageNum;
        this.getPeopleList();
      },
      // 更改分页查询条数
      changePageSize(pageSize) {
        this.pageNum = 1;
        this.pageSize = pageSize;
        // this.getPeopleList();
      },
      // 删除通知
      async deletePeople(id) {
        this.$Spin.show();
        let result = await peopleApi.deletePeople(id);
        this.$Spin.hide();
        this.$Message.success('删除消息成功!');
        this.getPeopleList();
      },
// 发送消息
// async sendPeople(id) {
//   this.$Spin.show();
//   let result = await peopleApi.sendPeople(id);
//   this.$Message.success('发送消息成功!');
//   this.$Spin.hide();
//   this.getPeopleList();
// },
      // 保存任务
      addOrUpdatePeople() {
        try {
          this.$refs['formRef'].validate(valid => {
            if (valid) {
              if (this.modalType == 'add') {
                this.addPeople();
              } else {
                this.editPeople();
              }
            }
          });
        } catch (e) {
          //TODO zhuoda sentry
          console.error(e);
        }
      },
      // 修改消息
      async editPeople() {
        try {
          this.loading = true;
          let result = await peopleApi.updatePeople(this.formData);
          this.$Message.success('修改成功');
          this.editModal = false;
          this.getPeopleList();
        } catch (e) {
          //TODO zhuoda sentry
          console.error(e);
          this.loading = false;
        }
      },
      // 保存消息
      async addPeople() {
        try {
          this.loading = true;
          let result = await peopleApi.addPeople(this.formData);
          this.$Message.success('添加成功');
          this.editModal = false;
          this.getPeopleList();
          this.loading = false;
        } catch (e) {
          //TODO zhuoda sentry
          console.error(e);
          this.loading = false;
        }
      },
      // 取消添加/修改
      cancelSave() {
        this.editModal = false;
        this.$refs['formRef'].resetFields();
      },
      // 重置
      refresh() {
        this.pageNum = 1;
        this.searchData.title = '';
        this.getPeopleList();
      }
    }
  };
</script>

<style scoped>

</style>

<style scoped>

</style>
